#!/usr/bin/env bash
# https://github.com/srs/gradle-node-plugin/issues/24

die() { echo "$@" 1>&2 ; exit 1; }

GRADLE_USER_HOME="${GRADLE_USER_HOME:-${HOME}/.gradle}"
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
# This should match the "workDir" setting in build.gradle
NODEJS=$GRADLE_USER_HOME/nodejs

platform=$(uname -s | tr '[:upper:]' '[:lower:]')

arch=$(uname -m | tr '[:upper:]' '[:lower:]')
case $arch in
x86_64)
    nodearch=x64
    ;;
x86)
    nodearch=x86
    ;;
esac

NODE_VERSION=$($DIR/gradlew npm_version -q | grep node: | awk -F"'" '{print $2}')
NODE_HOME="${NODE_HOME:-$NODEJS/node-v${NODE_VERSION}-${platform}-${nodearch}}"

if [ ! -d "$NODE_HOME" ]; then
  die "Could not find gradle npm"
fi
if [ ! -d "$DIR/frontend/node_modules" ]; then
  echo "Npm packages not found."
  echo "Running npm install... This will take some time"
  $DIR/gradlew frontend:npmInstall
fi

NPM_HOME="${NPM_HOME:-${NODE_HOME}/lib/node_modules/npm}"
NODE_MODULES_HOME="${NODE_MODULES_HOME:-$DIR/node_modules}"

PATH="${NODE_MODULES_HOME}:${NPM_HOME}:${NODE_HOME}:${PATH}"

pushd ./frontend
exec npm ${@}
